<?php
namespace app\common\service;

use app\common\logic\GoodsLogic;
use think\facade\Db;
use Imagick;
use ImagickPixel;

class ImageSpider extends Base {
    static $AUTH_CHECK = false; //默认必须登录
    public function createOrder(){
        $params = input();
        $sysset = Db::name('videospider_sysset')->find();
        $ordernum = logic('OrderLogic')->get_order_sn();
        $pay_money = 0;//余额支付金额
        $pay_score = 0;//积分支付金额
        $need_pay = 1;//是否需要支付
        $able_time = 0;//有效期

        $member_info = Db::name('users')->where(['user_id'=>$this->user_id])->field('id,videospider_time')->find();
        $end_time = $member_info['videospider_time']>time()?$member_info['videospider_time']:time();

        $pay_way = input('pay_way');
        if($end_time>time()){
            //在有效期内不用支付
            $pay_num = 0;
            $need_pay = 0;
        }else if($pay_way=='free'){
            //免费试用 查询已免费试用的次数
            $have_free = Db::name('videospider_order')->where(['status'=>1,'pay_way'=>'free','user_id'=>$this->user_id])->count();
            if($have_free>=$sysset['free_num']){
                return $this->json(['status'=>0,'data'=>'','msg'=>'免费试用次数已用完']);
            }
            $pay_num = 0;
            $need_pay = 0;
        }else if($pay_way=='once'){
            //单次
            $pay_num = $sysset['pay_num'];
        }else if($pay_way=='month'){
            //包月
            $pay_num = $sysset['pay_num_month'];
            $able_time = $end_time+86400*30;
        }else if($pay_way=='ji'){
            //包季度
            $pay_num = $sysset['pay_num_ji'];
            $able_time = $end_time+86400*90;
        }else if($pay_way=='year'){
            //包年
            $pay_num = $sysset['pay_num_year'];
            $able_time = $end_time+86400*365;
        }

        if($sysset['pay_type']==1){
            $pay_money = $pay_num;
        }else if($sysset['pay_type']==2){
            $pay_score = $pay_num;
        }else{
            $need_pay = 0;
        }


        //去除链接文字，提取完整链接
        preg_match(
            "/(https:|http:)(\/\/[A-Za-z0-9_#?.&=\/]+)([".chr(0xb0)."-".chr(0xf7)."][".chr(0xa1)."-".chr(0xfe)."])?(\s)?/i",
            $params['url'],
            $urls
        );
        if (!empty($urls)) {
            $url = $urls[0];
        }else{
            $url = $params['url'];
        }
        //$url = $params['url'];
        $data = [];
        $data['user_id'] = $this->user_id;
        $data['ordernum'] = $ordernum;
        $data['url'] = $url;
        $data['pay_money'] = $pay_money;
        $data['pay_score'] = $pay_score;
        $data['pay_way'] = $pay_way;
        $data['w_time'] = time();
        $data['able_time'] = $able_time;

        $oid = Db::name('videospider_order')->insertGetId($data);
        if($need_pay){

            $result = [
                'payorderid' => $payorderid??0,
                'need_pay' => $need_pay,
                'oid' => $oid,
                'type' => 'videospider'
            ];
            return ['status'=>1,'data'=>$result,'msg'=>'提交成功'];
        }else{
            //不需要支付时直接处理
            $res = logic('VideoSpider')->parseUrl($data['url']);
            $data_u = [];
            $data_u['err_msg'] = $data_u['msg'];
            if($res['status']){
                $data_u['video_url'] = $res['data']['url'];
                $data_u['video_cover'] = $res['data']['cover'];
                $data_u['video_title'] = $res['data']['title'];
            }
            $data_u['status'] = 1;
            Db::name('videospider_order')->where('id',$oid)->update($data_u);
            $res['data']['need_pay'] = 0;
            $res['data']['oid'] = $oid;
            return $res;
        }
    }


    //获取支持的平台
    public function getCategory(){
        //查询条件
        $where = [];
        $where[] = ['status','=',1];
        if(input('param.keyword')){
            $where[] = ['name','like','%'.input('param.keyword').'%'];
        }
        $datalist = Db::name('videospider_category')
            ->where($where)
            ->order('sort desc,id desc')
            ->field('id,name,pic')
            ->select()
            ->toArray();

        return $this->json(['status'=>1,'data'=>$datalist]);
    }
    //获取参数设置
    public function getSet(){
        $sysset = Db::name('videospider_sysset')->find();
        $pay_money = 0;//余额支付金额
        $pay_score = 0;//积分支付金额
        $need_pay = 0;//是否需要支付
        $money_type = '';
        if($sysset['pay_type']==1){
            $pay_money = $sysset['pay_num'];
            $need_pay = 1;
            $money_type = t('余额');
        }else if($sysset['pay_type']==2){
            $pay_score = $sysset['pay_num'];
            $need_pay = 1;
            $money_type = t('积分');
        }
        //查询已免费试用的次数
        $have_free = Db::name('videospider_order')->where(['status'=>1,'pay_way'=>'free','user_id'=>$this->user_id])->count();
        $free_num = $sysset['free_num']-$have_free;
        $pay_ways = [
            [
                'type'=>'free',
                'name'=>'免费试用',
                'num' => $sysset['free_num'],
                'desc' => '剩余'.$free_num.'次',
            ],
            [
                'type'=>'once',
                'name'=>'单次使用',
                'num' => $sysset['pay_num'],
                'desc' => '消费'.$sysset['pay_num'].$money_type
            ],
            [
                'type'=>'month',
                'name'=>'包月(30天)',
                'num' => $sysset['pay_num_month'],
                'desc' => '消费'.$sysset['pay_num_month'].$money_type
            ],
            [
                'type'=>'ji',
                'name'=>'包季(90天)',
                'num' => $sysset['pay_num_ji'],
                'desc' => '消费'.$sysset['pay_num_ji'].$money_type
            ],
            [
                'type'=>'year',
                'name'=>'包年(365天)',
                'num' => $sysset['pay_num_year'],
                'desc' => '消费'.$sysset['pay_num_year'].$money_type
            ],
        ];
        $member_info = Db::name('users')->where(['user_id'=>$this->user_id])->field('id,videospider_time')->find();
        $end_time = $member_info['videospider_time']>time()?$member_info['videospider_time']:0;
        $res = [
            'bgcolor' => $sysset['bgcolor'],
            'pay_money' => $pay_money,
            'pay_score' => $pay_score,
            'need_pay' => $need_pay,
            'pay_ways' => $pay_ways,
            'end_time' => $end_time>0?date('Y-m-d H:i',$end_time):''
        ];
        return $this->json(['status'=>1,'msg'=>'查询成功','data'=>$res]);
    }

    //获取订单详情
    public function getDetail(){
        $oid = input('id');
        $order = Db::name('videospider_order')->where('id',$oid)->find();
        $res = logic('VideoSpider')->parseUrl($order['url']);
        $data_u = [];
        $data_u['err_msg'] = $data_u['msg'];
        if($res['status']){
            $data_u['video_url'] = $res['data']['url'];
            $data_u['video_cover'] = $res['data']['cover'];
            $data_u['video_title'] = $res['data']['title'];
        }
        Db::name('videospider_order')->where('id',$oid)->update($data_u);
        //解析失败 退回余额
        if($res['status']==0 && $order['pay_way']=='once'){
            if($order['pay_money']>0){
                qianbao($this->user_id,-$order['pay_money'],$this->user_id,1,'视频解析订单退款,订单号: '.$order['ordernum']);
            }

        }
        return $res;
    }

    //获取订单列表
    public function getLists(){
        //分页数据
        $pagenum = input('post.pagenum');
        if(!$pagenum) $pagenum = 1;
        $pernum = 20;
        //查询条件
        $where = [];
        $where[] = ['status','=',1];

        $datalist = Db::name('videospider_order')
            ->where($where)
            ->page($pagenum,$pernum)
            ->order('id desc')
            ->field('id,ordernum,url,video_title,video_cover,video_url,status')
            ->select()
            ->toArray();

        return ['status'=>1,'data'=>$datalist];
    }

    //去水印
    public function delshuiyin(){
        $inputPath = 'E:\phpstudy_pro\WWW\check_domain\public\upload\test.jpg';
        $outputPath = 'E:\phpstudy_pro\WWW\check_domain\public\upload\test2.jpg';
        $watermarkColor = '#FDB9C6';// 水印的主要颜色，这里假设是白色
        $fuzziness = 30;  // 颜色匹配的容差 值越大，匹配的范围越广。
        $blurRadius = 10;  // 模糊半径 值越大，模糊效果越强。
        $iterations = 3;  // 处理迭代次数 增加迭代次数可能会提高效果，但也会增加处理时间。
        try {
            // 创建Imagick对象
            $image = new Imagick($inputPath);

            // 将水印颜色转换为ImagickPixel对象
            $targetColor = new ImagickPixel($watermarkColor);

            for ($i = 0; $i < $iterations; $i++) {
                // 创建一个遮罩，标识与水印颜色相近的区域
                $mask = clone $image;
                $mask->transparentPaintImage($targetColor, 0, $fuzziness, false);

                // 创建一个模糊版本的原图
                $blurred = clone $image;
                $blurred->blurImage($blurRadius, $blurRadius);

                // 将模糊图像合成到原图上，只在遮罩区域生效
                $image->compositeImage($blurred, Imagick::COMPOSITE_OVER, 0, 0, Imagick::CHANNEL_ALL);

                // 清理内存
                $mask->destroy();
                $blurred->destroy();
            }

            // 保存结果
            $image->writeImage($outputPath);

            // 清理内存
            $image->destroy();
            dump('ok');
        } catch (ImagickException $e) {
            echo 'Error: ' . $e->getMessage();
        }

    }
    //去马赛克
    public function delmasaike(){
        // 使用示例
        $inputPath = 'E:\phpstudy_pro\WWW\check_domain\public\upload\test3.jpg';
        $outputPath = 'E:\phpstudy_pro\WWW\check_domain\public\upload\test4.jpg';
        // 加载图像
        $image = imagecreatefromjpeg($inputPath);
        $width = imagesx($image);
        $height = imagesy($image);

        // 创建新图像
        $newImage = imagecreatetruecolor($width, $height);

        // 定义马赛克块的大小（假设为8x8像素）
        $blockSize = 8;

        // 遍历每个马赛克块
        for ($y = 0; $y < $height; $y += $blockSize) {
            for ($x = 0; $x < $width; $x += $blockSize) {
                // 获取块的颜色
                $rgb = imagecolorat($image, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // 获取右边和下边块的颜色（如果存在）
                $rightRgb = ($x + $blockSize < $width) ? imagecolorat($image, $x + $blockSize, $y) : $rgb;
                $bottomRgb = ($y + $blockSize < $height) ? imagecolorat($image, $x, $y + $blockSize) : $rgb;

                $rightR = ($rightRgb >> 16) & 0xFF;
                $rightG = ($rightRgb >> 8) & 0xFF;
                $rightB = $rightRgb & 0xFF;

                $bottomR = ($bottomRgb >> 16) & 0xFF;
                $bottomG = ($bottomRgb >> 8) & 0xFF;
                $bottomB = $bottomRgb & 0xFF;

                // 对块内的每个像素进行插值
                for ($by = 0; $by < $blockSize && ($y + $by) < $height; $by++) {
                    for ($bx = 0; $bx < $blockSize && ($x + $bx) < $width; $bx++) {
                        // 简单线性插值
                        $ratioX = $bx / $blockSize;
                        $ratioY = $by / $blockSize;

                        $newR = (int)($r + $ratioX * ($rightR - $r) + $ratioY * ($bottomR - $r));
                        $newG = (int)($g + $ratioX * ($rightG - $g) + $ratioY * ($bottomG - $g));
                        $newB = (int)($b + $ratioX * ($rightB - $b) + $ratioY * ($bottomB - $b));

                        // 确保颜色值在0-255范围内
                        $newR = max(0, min(255, $newR));
                        $newG = max(0, min(255, $newG));
                        $newB = max(0, min(255, $newB));

                        $newColor = imagecolorallocate($newImage, $newR, $newG, $newB);
                        imagesetpixel($newImage, $x + $bx, $y + $by, $newColor);
                    }
                }
            }
        }

        // 保存新图像
        imagejpeg($newImage, $outputPath, 100);

        // 释放内存
        imagedestroy($image);
        imagedestroy($newImage);
        dump('ok');exit;
    }
}
